<template>
  <EditModal title="修改油水井">
    <!-- 居中显示 关联管道信息 -->
    <div>
      <p style="text-align: center; background-color: #333232;"><strong>关联管道信息</strong></p>
    </div>
    <!-- 显示pipelineList中的数据中的管线编号，管线名称和一个序号-->
    <div class="pipeline-table">
      <div class="pipeline-header">
        <span class="pipeline-header-item">序号</span>
        <span class="pipeline-header-item">管线编号</span>
        <span class="pipeline-header-item">操作</span>
      </div>
      <div v-for="(pipeline, index) in data1.pipelineList" :key="pipeline.id" class="pipeline-row">
        <span class="pipeline-item">{{ index + 1 }}.</span>
        <span class="pipeline-item">
          <input v-model="pipeline.pipeCode" placeholder="请输入管线编号" />
        </span>
        <span class="pipeline-item">
          <button style="color:#007bff;margin-right: 10px;"  @click="removePipeline(index)">删除</button>
        </span>
      </div>
    </div>
    <!-- 增加按钮 -->
    <button style="color:#007bff;margin-bottom: 10px;"  @click="addPipeline">增加管线</button>
    <!-- 打印空行 -->
    <br />
    <hr />
    <br />
    <BaseForm />
    <template #prepend-footer>
    </template>
  </EditModal>
</template>

<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { updateWell } from '#/api/gis/well';
import type { EditWellParams } from '#/api/gis/well';
import { message } from 'ant-design-vue';
import { ref, nextTick } from 'vue';
import { z } from '#/adapter/form';

// 定义 pipelineList 的数据结构
interface Pipeline {
  id: string; // 假设每个管道有唯一标识
  pipeCode: string;
  pipeName: string;
}

// 定义 data 的完整结构
const data1 = ref<{
  id: string;
  wellCode: string;
  wellName: string;
  status: string;
  location: string;
  depth: string;
  remark: string;
  pipelineList: Pipeline[];
}>({
  id: '',
  wellCode: '',
  wellName: '',
  status: '',
  location: '',
  depth: '',
  remark: '',
  pipelineList: [],
});

const [EditModal, EditmodalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const modalData = EditmodalApi.getData<Record<string, any>>();
      console.log("modalData:", modalData); // Debugging info
      const actualData = modalData.data;
      data1.value = {
        id: actualData.id || '',
        wellCode: actualData.wellCode || '',
        wellName: actualData.wellName || '',
        status: actualData.status,
        location: actualData.location || '',
        depth: actualData.depth || '',
        remark: actualData.remark || '',
        pipelineList: Array.isArray(actualData.pipelineList)
          ? actualData.pipelineList.map((item: any) => ({
              id: item.id || '',
              pipeCode: item.pipeCode || '',
              pipeName: item.pipeName || '',
            }))
          : [],
      } as typeof data1.value; // Explicit type assertion

      console.log("modalData1:", data1.value); // Debugging info

      // Ensure BaseForm renders before setting initial values
      nextTick(() => {
        setTimeout(() => {
          if (data1.value) {
            const plainData = JSON.parse(JSON.stringify(data1.value));
            console.log('plainData:', plainData); // Debugging info

            // Process plainData.data values to meet form requirements
            if (plainData.location) {
              const locationParts = plainData.location.split(', ');
              if (locationParts.length === 2) {
                const longitude = locationParts[0].split(': ')[1];
                const latitude = locationParts[1].split(': ')[1];
                plainData.longitude = longitude;
                plainData.latitude = latitude;
              }
            }

            if (plainData.status) {
              plainData.status = plainData.status === '正常' ? 1 : 0;
            }

            if (plainData.remark === "---") {
              plainData.remark = "";
            }

            // Set initial values for BaseForm
            BaseFormApi.setValues(plainData, false);
            BaseFormApi.getValues().then((values) => {
              console.log('Retrieved values:', values); // Debugging info
            });

            // Ensure pipelineList is correctly assigned
            if (plainData.pipelineList) {
              data1.value.pipelineList = plainData.pipelineList;
            }
          }
        }, 100); // Delay by 100ms
      });
    }
  },
});

const [BaseForm, BaseFormApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入井编号',
        disabled: true,
      },
      fieldName: 'wellCode',
      label: '井编号',
      rules: "required",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入井名称',
      },
      fieldName: 'wellName',
      label: '井名称',
      rules: "required",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入经度',
      },
      fieldName: 'longitude',
      label: '经度',
      rules: z.string()
        .min(1, { message: '请输入经度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -180 && numValue <= 180;
        }, {
          message: '经度必须在 -180 到 180 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入纬度',
      },
      fieldName: 'latitude',
      label: '纬度',
      rules: z.string()
        .min(1, { message: '请输入纬度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -90 && numValue <= 90;
        }, {
          message: '纬度必须在 -90 到 90 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入井深',
      },
      fieldName: 'depth',
      label: '井深(米)',
      suffix: () => '米',
      rules: z.union([
        z.string().refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= 0;
        }, {
          message: '总接口数必须是一个有效的数字且大于等于0',
        }),
        z.number().min(0, { message: '总接口数必须是一个有效的数字且大于等于0' }),
      ])
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: '冻结',
            value: 0,
          },
          {
            label: '正常',
            value: 1,
          },
        ],
      },
      fieldName: 'status',
      label: '状态：',
      rules: "selectRequired",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入备注',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
});

// 定义一个自定义事件，用于在修改完数据后刷新页面
const emit = defineEmits(['refreshTable']);

function onSubmit(values: Record<string, any>) {
  const params = values as EditWellParams;
  params.location = `POINT(${params.longitude} ${params.latitude})`;
  updateWell(params).then(() => {
    EditmodalApi.close();
    message.success('修改油水井成功');
  }).catch((error) => {
    console.error('修改油水井失败:', error);
    message.error('修改油水井失败');
  });
  emit('refreshTable'); // 触发自定义事件
}

// 增加管线
function addPipeline() {
  const newPipeline: Pipeline = {
    id: Date.now().toString(), // 使用当前时间戳作为唯一标识
    pipeCode: '',
    pipeName: '',
  };
  data1.value.pipelineList.push(newPipeline);
}

// 删除管线
function removePipeline(index: number) {
  data1.value.pipelineList.splice(index, 1);
}
</script>

<style>
.pipeline-table {
  border-collapse: collapse;
  width: 100%;
}

.pipeline-header,
.pipeline-row {
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
}

.pipeline-item {
  width: 33.33%;
  text-align: left;
  padding: 5px;
  border-bottom: 1px solid #ddd;
}

.pipeline-header-item {
  width: 33.33%;
  text-align: left;
  padding: 5px;
  border-bottom: 1px solid #ddd;
  color: #ddd;
  font-weight: bold;
}

.pipeline-item input {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

</style>
